﻿using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestFilterSocket
{
    public class HansReceiveFilter : IReceiveFilter<HansRequestInfo>
    {
        public int leftBufferSize;

        public Encoding Encoder = Encoding.GetEncoding("gbk");

        public string StartMark = "!Start";

        public string EndMark = "$End";

        public int LeftBufferSize
        {
            get
            {
                return this.leftBufferSize;
            }
        }

        public IReceiveFilter<HansRequestInfo> NextReceiveFilter
        {
            get
            {
                return this;
            }
        }

        public FilterState State
        {
            get;
            private set;
        }

        public HansReceiveFilter(Encoding encoder, string startMark, string endMark)
        {
            this.Encoder = encoder;
            this.StartMark = startMark;
            this.EndMark = endMark;
        }

        public HansRequestInfo Filter(byte[] readBuffer, int offset, int length, bool toBeCopied, out int rest)
        {
            rest = 0;
            byte[] bytes = this.Encoder.GetBytes(this.StartMark);
            byte[] bytes2 = this.Encoder.GetBytes(this.EndMark);
            HansRequestInfo result;
            if (length < bytes.Length + bytes2.Length)
            {
                result = null;
            }
            else
            {
                byte[] array = new byte[length];
                Buffer.BlockCopy(readBuffer, offset, array, 0, length);
                string @string = this.Encoder.GetString(array, 0, bytes.Length);
                string string2 = this.Encoder.GetString(array, length - bytes2.Length, bytes2.Length);
                HansReceiveData hansReceiveData = new HansReceiveData();
                hansReceiveData.StartMark = this.StartMark;
                hansReceiveData.Key = Guid.NewGuid().ToString("B");
                hansReceiveData.BodyBuffer = new byte[length - bytes.Length - bytes2.Length];
                Buffer.BlockCopy(array, bytes.Length, hansReceiveData.BodyBuffer, 0, length - bytes.Length - bytes2.Length);
                hansReceiveData.EndMark = this.EndMark;
                hansReceiveData.BodyString = this.Encoder.GetString(hansReceiveData.BodyBuffer);
                this.leftBufferSize = length - bytes.Length - bytes2.Length;
                if (!@string.Equals(this.StartMark) || !string2.Equals(this.EndMark))
                {
                    result = null;
                }
                else
                {
                    result = new HansRequestInfo(hansReceiveData.Key, hansReceiveData);
                }
            }
            return result;
        }

        public void Reset()
        {
        }
    }
}